<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import PipnentInfoApi from '@/api/equip/pipnet'
const { required } = useValidator()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})
const FormSchemas = reactive<FormSchema[]>([
  {
    field: 'pnName',
    label: '片区名称',
    component: 'Input',
    colProps: {
      span: 20
    }
  },

  {
    field: 'parentId',
    label: '组织关联',
    component: 'TreeSelect',
    componentProps: {
      renderAfterExpand: false,
      showCheckbox: true,
      checkStrictly: true,
      checkOnClickNode: true,
      nodeKey: 'id',
      props: {
        label: 'label'
      }
    },
    optionApi: async () => {
      const res = await PipnentInfoApi.GetPnTopologyTree()
      return res.data
    },
    colProps: {
      span: 20
    }
  },
  {
    field: 'orderNum',
    label: '排序',
    component: 'InputNumber',
    colProps: {
      span: 20
    }
  }
])
const rules = reactive({
  fnName: [required()],
  parentId: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="FormSchemas" />
</template>
